package cn.edu.stu.syllabus.repository.oa.local;

import java.util.List;

import cn.edu.stu.syllabus.dao.OaInfoEntryDao;
import cn.edu.stu.syllabus.repository.oa.OaStarDataSource;
import cn.edu.stu.syllabus.utils.ListUtils;
import rx.Observable;

/**
 * Created by daidaijie on 2017/3/14.
 */

public class OaStarLocalDataSource implements OaStarDataSource {

    OaInfoEntryDao mOaInfoEntryDao;

    public OaStarLocalDataSource(OaInfoEntryDao oaInfoEntryDao) {
        this.mOaInfoEntryDao = oaInfoEntryDao;
    }


    @Override
    public void starOaInfoEntry(OaInfoEntry oaInfoEntry) {
        mOaInfoEntryDao.insertOrReplace(oaInfoEntry);
    }

    @Override
    public void unstarOaInfoEntry(OaInfoEntry oaInfoEntry) {
        OaInfoEntry oaInfoEntryInDb = getOaInfoEntryInDb(oaInfoEntry);
        mOaInfoEntryDao.delete(oaInfoEntryInDb);
    }

    @Override
    public boolean isExistEntry(OaInfoEntry oaInfoEntry) {
        return getOaInfoEntryInDb(oaInfoEntry) != null;
    }

    @Override
    public Observable<List<OaInfoEntry>> getStarOaInfoEntries(long lastPosition, int pageNum) {
        return Observable.just(getOaInfoEntriesInDb(lastPosition, pageNum));
    }

    private List<OaInfoEntry> getOaInfoEntriesInDb(long lastPosition, int pageNum) {
        List<OaInfoEntry> oaInfoEntries = mOaInfoEntryDao
                .queryBuilder()
                .where(OaInfoEntryDao.Properties.MLocalId.lt(lastPosition))
                .limit(pageNum)
                .orderDesc(OaInfoEntryDao.Properties.MLocalId)
                .build().list();


        return oaInfoEntries;
    }

    private OaInfoEntry getOaInfoEntryInDb(OaInfoEntry oaInfoEntry) {
        List<OaInfoEntry> oaInfoEntries = mOaInfoEntryDao
                .queryBuilder().where(OaInfoEntryDao.Properties.MRemoteId.eq(oaInfoEntry.getMRemoteId()))
                .build().list();
        if (ListUtils.getListSizeSafety(oaInfoEntries) == 0) {
            return null;
        } else {
            return oaInfoEntries.get(0);
        }
    }
}
